package com.example.menhoo.toollibrary.common.utils;

import android.text.TextUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.ArrayList;

/**
 * Created by yanglei on 17/1/8.
 */
public class StringUtil {
    public static String join(ArrayList<String> list,String ch){
        StringBuffer sb=new StringBuffer();
        for(String item : list){

            if(list.indexOf(item)!=0){
                sb.append(ch);
            }
            sb.append(item);
        }
        return sb.toString();

    }
    public static  boolean isEmpty(String text){
        return TextUtils.isEmpty(text);
    }

    /**
     * 转换一个字符串
     * @param str
     * @return
     */
    public static String getStringPinYin(String str) {
        StringBuilder sb = new StringBuilder();
        String tempPinyin = null;
        for(int i = 0; i < str.length(); ++i) {
            tempPinyin =getCharacterPinYin(str.charAt(i));
            if(tempPinyin == null) {
                // 如果str.charAt(i)非汉字，则保持原样
                sb.append(str.charAt(i));
            }else {
                sb.append(tempPinyin);
            }
        }
        return sb.toString();
    }
    /**
     * 转换单个字符
     * @param c
     * @return
     */
    public static String getCharacterPinYin(char c) {
        String[] pinyin=null;
        HanyuPinyinOutputFormat format = null;
        format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        try {
            pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
        }catch(BadHanyuPinyinOutputFormatCombination e){
            e.printStackTrace();
        }
        // 如果c不是汉字，toHanyuPinyinStringArray会返回null
        if(pinyin == null) return null;
        // 只取一个发音，如果是多音字，仅取第一个发音
        return pinyin[0];
    }
}
